package com.hctforgreen.greenservice;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookClickListEntity;
import com.hctforgreen.greenservice.model.ColumnListEntity.ColumnEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.ui.adapter.DebugBooksColumnListAdapter;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;

/**
 * 1.5期 从DebugAcivity 进入的 "资料目录"列表页
 * 
 * @author Tallen Zhai
 * 
 */
public class DebugBooksActivity extends ParentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_debug_books);
		initSkinLayout();
		initTitleButtonBar();
		initWindow();
		initSearchBar();
		initInstallInfo();// 安装信息
	}

	/**
	 * 跳转至安装信息
	 */
	private void initInstallInfo() {
		TextView tvInfo = (TextView) findViewById(R.id.install_info);
		tvInfo.setText("     " + getString(R.string.debug_books_install_info));
		findViewById(R.id.lyt_install_info).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {// 安装信息

						Intent intent = new Intent(DebugBooksActivity.this,
								InstallInfosActivity.class);
						MachineEntity entity = (MachineEntity) getIntent()
								.getSerializableExtra(
										HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY);
						intent.putExtra("barCodeId", entity.barcode + "");
						startActivity(intent);
					}
				});

	}

	// private void initSkinLayout(){
	// View parentLyt = (View) findViewById(R.id.lyt_parent);
	// parentLyt.setBackgroundResource(ThemeStoreUtil.getSkinId(this));
	// }
	private void initTitleButtonBar() {

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
			}
		});

		MachineEntity entity = (MachineEntity) getIntent()
				.getSerializableExtra(
						HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY);
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		HctController controller = new HctController(DebugBooksActivity.this);

		SerieEntity sEntity = controller
				.selectSerieEntityFromDb(entity.seriesId);
		if (sEntity != null) {
			titleTv.setText(sEntity.name);
		}

	}

	private void initWindow() {
		MachineEntity entity = (MachineEntity) getIntent()
				.getSerializableExtra(
						HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY);

		getBookClick(entity, "");

	}

	private void getBookClick(final MachineEntity entity, final String sKeyword) {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_list_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_list_reload);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				HctResult hctResult = new HctResult();

				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;

					BookClickListEntity clickListEntity = (BookClickListEntity) hctResult.data;

					getAllColumnLst(entity, sKeyword, clickListEntity);
					break;
				case HctConstants.STATUS_FAILD:

					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					getAllColumnLst(entity, sKeyword, null);
					break;
				}

			}

		};
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							DebugBooksActivity.this);

					HctResult result = controller.getBookClick(entity.id);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void getAllColumnLst(final MachineEntity entity,
			final String sKeyword, final BookClickListEntity clickListEntity) {

		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_list_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_list_reload);
		final Button reloadBtn = (Button) findViewById(R.id.btn_default_list_reload);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;

					ArrayList<ColumnEntity> entities = (ArrayList<ColumnEntity>) hctResult.data;

					renderBookCatalog(entities, entity, sKeyword,
							clickListEntity);

					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							getAllColumnLst(entity, sKeyword, clickListEntity);
						}
					});
					break;
				}
			}

			private void addTechnicalServiceBook(
					ArrayList<ColumnEntity> entities) {
				ColumnEntity cEntity = new ColumnEntity();

				cEntity.name = getString(R.string.technical_service_book_hint);
				entities.add(cEntity);
			}

			private void renderBookCatalog(ArrayList<ColumnEntity> entities,
					final MachineEntity entity, final String sKeyword,
					final BookClickListEntity clickListEntity) {
				View convertView = findViewById(R.id.lyt_parent);
				ListView dataLv = (ListView) convertView
						.findViewById(R.id.lst_default_list);

				dataLv.setVisibility(View.VISIBLE);

				if (!sKeyword.equals("")) {
					ArrayList<ColumnEntity> hasDataList = initHasDataList(entities);
					addTechnicalServiceBook(hasDataList);
					new DebugBooksColumnListAdapter(DebugBooksActivity.this,
							convertView, dataLv, hasDataList, entity,
							clickListEntity);
				} else if (sKeyword.equals("")) {
					addTechnicalServiceBook(entities);
					new DebugBooksColumnListAdapter(DebugBooksActivity.this,
							convertView, dataLv, entities, entity,
							clickListEntity);
				}

			}

			private ArrayList<ColumnEntity> initHasDataList(
					ArrayList<ColumnEntity> entities) {
				ArrayList<ColumnEntity> hasDataList = new ArrayList<ColumnEntity>();
				for (ColumnEntity cEntity : entities) {
					if (cEntity.dataList != null && cEntity.dataList.size() > 0) {
						hasDataList.add(cEntity);
					}
				}

				return hasDataList;
			}

		};

		loadLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 用此法屏蔽掉FrameLayout下面Layout的点击事件
			}
		});
		reloadLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 用此法屏蔽掉FrameLayout下面Layout的点击事件
			}
		});
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							DebugBooksActivity.this);

					HctResult result = controller.getAllColumnsFromDb(entity,
							sKeyword);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		ImageView searchIconIv = (ImageView) findViewById(R.id.iv_search_icon);
		searchIconIv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		searchInputEt.clearFocus();
	}

	private void initSearchBar() {
		final MachineEntity entity = (MachineEntity) getIntent()
				.getSerializableExtra(
						HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY);

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		final ImageButton clearBtn = (ImageButton) findViewById(R.id.btn_clear);

		searchInputEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String sInput = searchInputEt.getText().toString().trim();
				if (sInput.equals("")) {
					clearBtn.setVisibility(View.GONE);
				} else if (!sInput.equals("")) {
					clearBtn.setVisibility(View.VISIBLE);
				}
			}

		});

		searchInputEt.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH
						|| keyCode == KeyEvent.KEYCODE_UNKNOWN
						|| keyCode == KeyEvent.KEYCODE_ENTER) {
					String sSearchKey = searchInputEt.getEditableText()
							.toString().trim();

					if (!sSearchKey.equals("")) {
						getBookClick(entity, sSearchKey);
					} else if (sSearchKey.equals("")) {
						initWindow();
					}

					KeyboardUtil keyboardUtil = new KeyboardUtil();
					keyboardUtil.hideSoftKeyboard(v);
					clearFocus();
					return true;
				}
				return false;
			}

		});

		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				searchInputEt.setText("");
				initWindow();
			}
		});

	}
}
